package com.itcam.socket_.udp_;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * Author:Cammy.Wu
 * Date:2024-05-15
 * Description:加入完整异常处理方式——接收方
 */

public class ReceiveDemo04 {
    public static void main(String[] args) {
        System.out.println("李大帅上线了...");
        DatagramSocket datagramSocket = null;
        try {
            // 1.创建套接字：指定接收方的端口
            datagramSocket = new DatagramSocket(8990);
            while (true) {
                // 2.有一个空的数据包，打算用来接受对方传过来的数据包
                byte[] bytes = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
                // 3.接收到对方的数据包，然后放入datagramPacket数据包中填充
                datagramSocket.receive(datagramPacket);// 接收完以后datagramPacket里面就填充好了内容

                // 4.取出数据
                byte[] data = datagramPacket.getData();
                String str = new String(data, 0, datagramPacket.getLength());// datagramPacket.getLength()数组中有效长度
                System.out.println("袁天罡对我说：" + str);
                if (str.equals("byebye")) {
                    System.out.println("不良帅愤然离去...李星云开始怀疑自己");
                    break;
                }

                // 李星云的回复
//        String s = "天下大同";
                Scanner sc = new Scanner(System.in);
                System.out.print("李星云：");
                String s = sc.next();
                byte[] b = s.getBytes();
                DatagramPacket datagramPacket_ = new DatagramPacket(b, b.length, InetAddress.getByName("localhost"), 8989);
                datagramSocket.send(datagramPacket_);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5.关闭资源
            datagramSocket.close();
        }

    }
}
